//
//  HomeViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/19.
//

import UIKit
import TCCKit
import CoreBluetooth

class HomeViewController: EPViewController {
    @IBOutlet var startBtn: UIButton!
    var rightBtn:UIButton?
    var array = [CBPeripheral]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    
    override func initUI() {
        self.title = LS("首页")
        self.startBtn.isEnabled = false
        self.backBtn?.isHidden = true
        self.rightBtn = UIButton(type: .custom)
        self.rightBtn?.tag = 302
        self.rightBtn?.frame = CGRect(x: 0, y: kUIStatusBarHeight + 5, width: 70, height: 34)
        self.rightBtn?.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        self.rightBtn?.setTitle(LS("历史数据"), for: .normal)
        self.rightBtn?.setTitleColor("#005BBA".color(), for: .normal)
        self.rightBtn?.titleLabel?.font = font(14)
        let backItem = UIBarButtonItem(customView: self.rightBtn!)
        //self.navigationItem.rightBarButtonItem = backItem
        self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black, .font:font(18)]
        
        self.tableViewStyle = .grouped
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.hiddenMJRefresh()
        self.tableView.tableHeaderView = UIView(frame: .zero)
        self.tableView.register(HomeCell.nib(), forCellReuseIdentifier: HomeCell.ID())
        self.tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview().inset(20)
            make.bottom.equalTo(self.startBtn.snp.top).offset(-20)
        }
    }
    
    @objc @IBAction func actionForBtn(_ sender: UIButton) {
        if BLE.connectedPeripherals.count <= 0{
            CCHud.start("当前未连接设备", stopTime: 1)
        }
        let vc = StartViewController()
        self.push(vc, true)
    }
    
    func action(_ sender: UIButton, _ index:Int){
        switch sender.tag{
        case 202:///断开
            if BLE.connectedPeripherals.count > index{
//                CCHud.start()
                let per = BLE.connectedPeripherals[index]
                BLE.disConnect(per)
            }
        default:
            break
        }
    }
    
}
//MARK: - 蓝牙相关通知
extension HomeViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(actionForBLESDataUpdate), BLEData.dataupdate.ack)
        NotifyTool.add(self, #selector(actionForBLEStatus), BLEStatusUpdateNotifyName)
    }
    @objc func actionForBLESDataUpdate(_ notify:Notification){
        tableView.reloadData()
    }
    @objc func actionForBLEStatus(){
        startBtn.isEnabled = BLE.connectedPeripherals.count > 0
        startBtn.bgHexColor = startBtn.isEnabled ? "#005BBA" : "#CFCFCF"
        tableView.reloadData()
    }
}

//MARK: - UITableViewDataSource
extension HomeViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        array = BLE.connectedPeripherals
        switch array.count {
        case  0:
            return 1
        case 1:
            return 2
        default:
            return array.count
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeCell.ID()) as! HomeCell
        cell.bgView.isHidden = array.count > indexPath.section
        cell.content.isHidden = true
        if array.count > indexPath.section {
            let per = array[indexPath.section]
            cell.name.text = per.model.name
            cell.electNum.text = "电量: " + (per.model.ison ? "\(per.model.elect)" : "-") + "%"
        }
        cell.block = {[weak self] title in
            self?.action(title, indexPath.section)
        }
        return cell
    }
    
    
}
//MARK: - UITableViewDelegate
extension HomeViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! HomeCell
        if cell.bgView.isHidden == false {
            let vc = SearchViewController()
            self.push(vc, true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
